import React, { useEffect, useState } from 'react';
import { message, Spin, Empty } from 'antd';
import classnames from 'classnames';
import { connect } from 'umi';

import { isSuccess } from '@/utils/request';
import { withRoutePage } from '@/utils/enhanceUtils';
import { queryConfig } from '@/services/salaryManage/salaryChart';
import { getOrganizationList } from '@/services/Organization/orgmanage';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OrganizationSelect from '@/components/OrganizationSelect';

import { convertTreeToArray } from '@/pages/SalaryManage/utils/treeUtil';
import { getCurrentCompanyCode } from '@/pages/SalaryManage/utils';
import { useHandleRefreshMessage } from '@/pages/SalaryManage/utils/tabMessageUtil';

import SalaryTotal from './SalaryTotal';
import MyCharts from './MyCharts';
import { isEmptyObj } from './paramMap';

import styles from './style.less';

const PerspectivePic = ({ dispatch, selectOrganizationCode }) => {
    const [configState, setConfigState] = useState({})
    const [loading, setLoading] = useState(false)
    const [organizationTreeData, setOrganizationTreeData] = useState([])

    useEffect(() => {
        const resetInit = async () => {
            setLoading(true)
            const response = await getOrganizationList({ organizationPermissions: 1, showTreeFlag: 1 })
            setLoading(false)
            if (!isSuccess(response)) {
                message.error(response.message);
                return
            }
            setOrganizationTreeData(response)

            const orgList = convertTreeToArray(
                response.data,
                'children',
                org => org.organizationType === 1 || org.organizationType === 2
            );

            // 默认取当前行政机构
            const companyCode = selectOrganizationCode || getCurrentCompanyCode();
            const currentCompanyOrg = orgList.find(org => org.organizationCode === companyCode);
            // 当前行政机构不存在时取第1个
            const defaultSelectOrg = currentCompanyOrg || orgList?.[0];

            const defaultSelectCode = defaultSelectOrg?.organizationCode;
            dispatch({
                type: 'perspectiveOrgModel/setOrg',
                payload: {
                    selectOrganizationCode: defaultSelectCode
                }
            });
        };
        resetInit()
    }, [])

    useEffect(() => {
        const initFn = async () => {
            setLoading(true)
            const configParam = await queryConfig({ organizationCode: selectOrganizationCode })
            setLoading(false)
            if (isSuccess(configParam)) {
                setConfigState(configParam.data)
            } else {
                message.error(configParam.msg);
            }
        }
        if (selectOrganizationCode) {
            initFn()
        }
        return () => {
            setConfigState({})
        }
    }, [selectOrganizationCode])

    const changeOrgCode = val => {
        dispatch({
            type: 'perspectiveOrgModel/setOrg',
            payload: {
                selectOrganizationCode: val
            }
        });
    }

    useHandleRefreshMessage()

    return (
        <PageHeaderWrapper type="success">
            <Spin spinning={loading}>
                <div className={styles.chartWrapper}>
                    <div className={classnames(styles.chartHeader, styles.header)}>
                        <div className={styles.title}>薪资透视表</div>
                        <div className={styles.orgRight}>
                            <OrganizationSelect
                                style={{ width: 220 }}
                                value={selectOrganizationCode}
                                allowClear={false}
                                treeDataFromProp
                                dropdownMatchSelectWidth
                                treeDataList={organizationTreeData}
                                onChange={changeOrgCode} />
                        </div>
                    </div>
                    {isEmptyObj(configState) ?
                        (
                            <div className={styles.emptyMain}>
                                <Empty />
                            </div>
                        )
                        :
                        (
                            <>
                                <SalaryTotal
                                    organizationCode={selectOrganizationCode}
                                    globalInfo={configState.globalInfo} />
                                <MyCharts
                                    loading={loading}
                                    organizationCode={selectOrganizationCode}
                                    specialInfoList={configState.specialItemInfoList} />
                            </>
                        )
                    }
                </div>
            </Spin>
        </PageHeaderWrapper>
    )
}

export default withRoutePage(
    connect(({ perspectiveOrgModel }) => ({
        ...perspectiveOrgModel
    }))(PerspectivePic)
)
